package com.guojiaming.interview.first.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 思路,实现一个圆,图片串在圆形上面实时计算图片的位置,并且绘制
 * 1.圆心的位置为屏幕的偏下的中心(暂定控件高度-400)圆的半径为控件高度-400-图片高度/2
 * 2.每隔20度有一个图片
 * 3.转动圆形时修改对应的度数
 * 4.默认时第一个图片在0度的位置,其它的每个增加20度
 */
public class CustomRotateImageView extends View {
    public static final int WIDTH = 220 * 2;
    public static final int HEIGHT = 360 * 2;
    public static final int DEFAULT_DEGREE = 20;
    public static final int CHANGE_DEGREE = 8;

    private List<String> images;
    private Map<String, Bitmap> mBitmaps;
    RequestOptions options;
    private double radius;
    private double offsetX;
    private double startX;
    /**
     * 圆的转动偏移度数
     */
    private int offset = 0;


    public CustomRotateImageView(Context context) {
        super(context);
        initView();
    }

    public CustomRotateImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public CustomRotateImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        images = new ArrayList<>();
        mBitmaps = new HashMap<>();
        options = new RequestOptions().centerCrop().override(WIDTH, HEIGHT);
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = motionEvent.getX();
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        offsetX = motionEvent.getX() - startX;
                        onSlide(offsetX < 0);
                        break;
                }
                return true;
            }
        });
    }

    private void onSlide(boolean left) {
        offset += left ? CHANGE_DEGREE : -CHANGE_DEGREE;
        invalidate();
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //圆的半径为圆心距离到控件顶部的距离减去图片高度的一半
        radius = getCenterY() - (HEIGHT >> 1);
        super.onDraw(canvas);
        drawImages(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    public void addImages(String image) {
        this.images.add(image);
        loadImages();
    }

    //加载所有的图片
    private void loadImages() {
        for (final String image : images) {
            if (mBitmaps.containsKey(image)) {
                continue;
            }
            Glide.with(this).asBitmap().load(image).apply(options).listener(new RequestListener<Bitmap>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                    mBitmaps.put(image, resource);
                    invalidate();
                    return true;
                }
            }).submit();
        }
    }

    private void drawImages(Canvas canvas) {
        for (int i = 0; i < images.size(); i++) {
            Bitmap bitmap = mBitmaps.get(images.get(i));
            if (bitmap != null) {
                //计算图片所处的度数
                float rotate = getRotate(i);
                //计算图片的x位置
                int x = getX(i, bitmap);
                //计算图片的y位置
                int y = getY(i, bitmap);
                //绘制一个图片
                drawOneImage(canvas, bitmap, x, y, rotate);
            }
        }
    }

    //圆心的x位置
    private double getCenterX() {
        return getWidth() >> 1;
    }

    //圆心的y位置
    private double getCenterY() {
        return getHeight() - 400;
    }

    //计算图片的角度
    private float getRotate(int index) {
        return offset + -index * DEFAULT_DEGREE;
    }

    //计算图片的x位置
    //x的位置可以通过度数相对的三角函数求出
    private int getX(int index, Bitmap bitmap) {
        double center = getCenterX();
        double distance = Math.sin(Math.toRadians(getRotate(index))) * radius;
        return Double.valueOf(center - distance).intValue() - bitmap.getWidth() / 2;
    }

    //计算图片的y位置
    private int getY(int index, Bitmap bitmap) {
        double center = getCenterY();
        double distance = Math.cos(Math.toRadians(getRotate(index))) * radius;
        return Double.valueOf(center - distance).intValue() - bitmap.getHeight() / 2;
    }

    private void drawOneImage(final Canvas canvas, final Bitmap image, int x, int y, float rotate) {
        Matrix matrix = new Matrix();
        //图片的位置
        matrix.setTranslate(x, y);
        //旋转图片,以图片自己为中心
        matrix.postRotate(-rotate, x + (image.getWidth() >> 1), y + (image.getHeight() >> 1));
        //绘制图片
        canvas.drawBitmap(image, matrix, null);
    }
}
